<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页 - 家电维修系统</title>
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <script th:src="@{/js/bootstrap.bundle.min.js}"></script>
    <style>
        #map {
            height: 400px;
            width: 100%;
        }
        .order-list {
            max-height: 500px;
            overflow-y: auto;
        }
        /* 轮播图样式 */
        .carousel {
            margin-bottom: 2rem;
        }
        .carousel-item {
            height: 500px;
        }
        .carousel-item img {
            object-fit: cover;
            height: 100%;
        }
        .carousel-caption {
            background: rgba(0, 0, 0, 0.5);
            padding: 20px;
            border-radius: 10px;
        }
        .carousel-caption h5 {
            font-size: 1.8rem;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .carousel-caption p {
            font-size: 1.1rem;
        }
        .carousel-indicators {
            margin-bottom: 1rem;
        }
        .carousel-indicators button {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin: 0 5px;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="#">家电维修系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link active" href="#">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/orders">我的订单</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/profile">个人资料</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/announcements">公告</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/forum">论坛</a>
                    </li>
                </ul>
                <div class="d-flex">
                    <span class="navbar-text me-3" id="userInfo"></span>
                    <button class="btn btn-outline-light" onclick="logout()">退出</button>
                </div>
            </div>
        </div>
    </nav>

    <div th:replace="common/announcement :: announcement_bell"></div>

    <!-- 轮播图 -->
    <div id="mainCarousel" class="carousel slide" data-bs-ride="carousel">
        <div class="carousel-indicators">
            <button type="button" data-bs-target="#mainCarousel" data-bs-slide-to="0" class="active"></button>
            <button type="button" data-bs-target="#mainCarousel" data-bs-slide-to="1"></button>
            <button type="button" data-bs-target="#mainCarousel" data-bs-slide-to="2"></button>
        </div>
        <div class="carousel-inner">
            <div class="carousel-item active">
                <img src="https://vaccine-hcf.oss-cn-hangzhou.aliyuncs.com/4.png" class="d-block w-100" alt="维修服务">
                <div class="carousel-caption d-none d-md-block">
                    <h5>专业维修服务</h5>
                    <p>快速响应，专业维修，让您的家电焕然一新</p>
                </div>
            </div>
            <div class="carousel-item">
                <img src="https://vaccine-hcf.oss-cn-hangzhou.aliyuncs.com/3.png" class="d-block w-100" alt="维修团队">
                <div class="carousel-caption d-none d-md-block">
                    <h5>经验丰富的维修团队</h5>
                    <p>持证上岗，经验丰富，为您提供最优质的服务</p>
                </div>
            </div>
            <div class="carousel-item">
                <img src="https://vaccine-hcf.oss-cn-hangzhou.aliyuncs.com/2.png" class="d-block w-100" alt="服务保障">
                <div class="carousel-caption d-none d-md-block">
                    <h5>服务保障</h5>
                    <p>质保服务，售后无忧，让您放心使用</p>
                </div>
            </div>
            <div class="carousel-item">
                <img src="https://vaccine-hcf.oss-cn-hangzhou.aliyuncs.com/1.png" class="d-block w-100" alt="服务保障">
                <div class="carousel-caption d-none d-md-block">
                    <h5>服务保障</h5>
                    <p>质保服务，售后无忧，让您放心使用</p>
                </div>
            </div>
        </div>
        <button class="carousel-control-prev" type="button" data-bs-target="#mainCarousel" data-bs-slide="prev">
            <span class="carousel-control-prev-icon"></span>
            <span class="visually-hidden">Previous</span>
        </button>
        <button class="carousel-control-next" type="button" data-bs-target="#mainCarousel" data-bs-slide="next">
            <span class="carousel-control-next-icon"></span>
            <span class="visually-hidden">Next</span>
        </button>
    </div>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-8">
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="card-title mb-0">维修预约</h5>
                    </div>
                    <div class="card-body">
                        <form id="repairForm">
                            <div class="mb-3">
                                <label for="applianceType" class="form-label">家电类型</label>
                                <select class="form-select" id="applianceType" name="applianceType" required>
                                    <option value="">请选择家电类型</option>
                                    <option value="空调">空调</option>
                                    <option value="冰箱">冰箱</option>
                                    <option value="洗衣机">洗衣机</option>
                                    <option value="热水器">热水器</option>
                                    <option value="电视">电视</option>
                                    <option value="其他">其他</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="description" class="form-label">故障描述</label>
                                <textarea class="form-control" id="description" name="description" rows="3" required></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="address" class="form-label">维修地址</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="address" name="address" required>
                                    <button class="btn btn-outline-secondary" type="button" id="searchAddress">搜索</button>
                                </div>
                                <div id="map" class="mt-3"></div>
                                <small class="form-text text-muted">您可以在地图上直接点击选择位置，或输入地址后点击搜索</small>
                            </div>
                            <div class="mb-3">
                                <label for="appointmentTime" class="form-label">预约时间</label>
                                <input type="datetime-local" class="form-control" id="appointmentTime" name="appointmentTime" required>
                            </div>
                            <button type="submit" class="btn btn-primary">提交预约</button>
                        </form>
                    </div>
                </div>

            </div>

            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">我的订单</h5>
                    </div>
                    <div class="card-body order-list">
                        <div id="orderList"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=spEZ8x14LoDN10ejoQD7GdxOEJYOwqcw"></script>
    <script src="/js/request.js"></script>
    <div th:replace="common/announcement :: announcement_script"></div>
    <script>
        let map;
        let markers = [];
        let currentUser = null;
        let geocoder;

        // 获取用户信息
        function getUserInfo() {
            if (!checkLoginStatus()) return;

            $.ajax({
                url: '/api/user/profile',
                type: 'GET',
                success: function(response) {
                    console.log('获取到的用户信息:', response);
                    if (response && response.id) {
                        currentUser = response;
                        $('#userInfo').text('欢迎，' + response.realName);
                        loadOrders();
                    }
                }
            });
        }

        // 加载订单列表
        function loadOrders() {
            if (!currentUser || !currentUser.id) return;

            $.ajax({
                url: '/api/order/user/' + currentUser.id,
                type: 'GET',
                success: function(orders) {
                    const orderList = $('#orderList');
                    orderList.empty();
                    orders.forEach(order => {
                        orderList.append(`
                            <div class="card mb-2">
                                <div class="card-body">
                                    <h6 class="card-title">${order.applianceType}</h6>
                                    <p class="card-text">状态：${getStatusText(order.status)}</p>
                                    <p class="card-text">预约时间：${new Date(order.appointmentTime).toLocaleString()}</p>
                                </div>
                            </div>
                        `);
                    });
                }
            });
        }

        // 获取状态文本
        function getStatusText(status) {
            const statusMap = {
                0: '待接单',
                1: '已接单',
                2: '维修中',
                3: '已完成',
                4: '已取消'
            };
            return statusMap[status] || '未知状态';
        }

        // 初始化百度地图
        function initMap() {
            map = new BMap.Map("map");
            let point = new BMap.Point(116.404, 39.915); // 默认北京市中心
            map.centerAndZoom(point, 12);
            map.enableScrollWheelZoom();
            map.addControl(new BMap.NavigationControl());
            
            geocoder = new BMap.Geocoder();
            
            // 点击地图事件
            map.addEventListener("click", function(e) {
                setMarker(e.point);
                // 根据坐标获取地址
                geocoder.getLocation(e.point, function(result) {
                    if (result) {
                        $('#address').val(result.address);
                    }
                });
            });
        }

        // 设置标记点
        function setMarker(point) {
            map.clearOverlays();
            let marker = new BMap.Marker(point);
            map.addOverlay(marker);
            map.panTo(point);
        }

        // 搜索地址
        $('#searchAddress').click(function() {
            let address = $('#address').val();
            if (address) {
                geocoder.getPoint(address, function(point) {
                    if (point) {
                        setMarker(point);
                        map.centerAndZoom(point, 15);
                    } else {
                        alert("未找到该地址，请输入更详细的地址信息");
                    }
                });
            }
        });

        // 提交维修预约
        $('#repairForm').on('submit', function(e) {
            e.preventDefault();
            
            if (!checkLoginStatus()) return;
            if (!currentUser || !currentUser.id) {
                alert('请先登录');
                window.location.href = '/login';
                return;
            }

            const formData = {
                userId: currentUser.id,
                applianceType: $('#applianceType').val(),
                description: $('#description').val(),
                address: $('#address').val(),
                appointmentTime: $('#appointmentTime').val().replace('T', ' ') + ':00',
                status: 0,  // 添加状态字段，0表示待接单
                createTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
                updateTime: new Date().toISOString().slice(0, 19).replace('T', ' ')
            };
            
            // 使用百度地图地理编码服务将地址转换为经纬度
            const geocoder = new BMap.Geocoder();
            geocoder.getPoint(formData.address, function(point) {
                if (point) {
                    formData.latitude = point.lat;
                    formData.longitude = point.lng;
                    
                    // 发送包含经纬度的表单数据
                    $.ajax({
                        url: '/api/order',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(formData),
                        headers: {
                            'Authorization': 'Bearer ' + localStorage.getItem('token')
                        },
                        success: function(response) {
                            console.log('预约成功:', response);
                            alert('预约成功，请等待维修人员联系您');
                            $('#repairForm')[0].reset();
                            loadOrders();
                        },
                        error: function(xhr, status, error) {
                            console.error('预约失败:', error);
                            alert('预约失败，请检查地址是否正确或重试');
                        }
                    });
                } else {
                    alert('无法解析该地址的位置，请输入更详细的地址');
                }
            });

        });

        // 退出登录
        function logout() {
            localStorage.removeItem('token');
            window.location.href = '/login';
        }

        // 页面加载完成后初始化
        $(document).ready(function() {
            if (checkLoginStatus()) {
                getUserInfo();
            }
            initMap(); // 初始化地图
        });
    </script>
</body>
</html> 